ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
-- 获取用户请求的参数 (请求url链接的"?"后的参数)
local uri_args = ngx.req.get_uri_args()
-- 请求参数里的"id"参数的值
local id = uri_args["id"]


local function close_db(db)
if not db then
	return
end
db:close()
end	


-- 连接mysql数据库
local db = mysql:new()
db:set_timeout(1000)
-- 连接信息，host，port，database，user，password
local props = {
host = "47.96.8.149",
port = 3306,
database = "his_cloud_agent",
user = "root",
password = "lulutong321"
}
-- 获取数据库连接
local res, err, errno, sqlstate = db:connect(props)
if not res then  
	ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
	return close_db(db)  
end 
-- sql语句
local select_sql = "SELECT * FROM dic_agent_subject WHERE agent_id ="..ngx.quote_sql_str(id)
-- 执行查询语句
res = db:query(select_sql)
-- 关闭数据库
if not res then	
	ngx.say("select rows error:",err,",errno:",errno,",sqlstate:",sqlstate)
	return close_db(db)
end

-- redis
local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)
-- redis的ip地址及端口
local ip ="47.96.8.149"
local port = 6379
red:connect(ip,port)
-- redis密码，如果没有就直接注释掉
red:auth("123")

--调用API获取数据
local resp, err = red:get("hello")
if not resp then
    ngx.say("get msg error : ", err)
    return close_redis(red)
end  
-- 存储,key="content_1",value=res的json类型,(res为mysql数据库里查询出的数据）
red:set("content_"..id,cjson.encode(res))
red:close()


-- 输出true
ngx.say(cjson.encode(res))
